package com.rybbaby.tss.front.tssMemberPackage.controller;


import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.consts.RoleConsts;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.*;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.core.web.service.IBaseService;
import com.rybbaby.tss.core.web.service.IViewService;
import com.rybbaby.tss.front.tssMemberPackage.entity.ExportEntity.ErrorMessage;
import com.rybbaby.tss.front.tssMemberPackage.entity.TssMemberPackage;
import com.rybbaby.tss.front.tssMemberPackage.entity.ViewMemberPackageStudent;
import com.rybbaby.tss.front.tssMemberPackage.entity.ViewTssMemberPackage;
import com.rybbaby.tss.front.tssMemberPackage.service.ITssMemberPackageService;
import com.rybbaby.tss.front.tssMemberPackage.service.IViewMemberPackageStudentService;
import com.rybbaby.tss.front.tssMemberPackage.service.ImportExcelService;
import com.rybbaby.tss.front.tssPackage.service.ITssPackageService;
import com.rybbaby.tss.front.tssPayment.entity.TssPayment;
import com.rybbaby.tss.front.tssPayment.service.ITssPaymentService;
import com.rybbaby.tss.front.tssStudent.entity.TssStudent;
import com.rybbaby.tss.front.tssStudent.service.ITssStudentService;
import com.rybbaby.tss.platform.sysAdminUser.entity.SysAdminUser;
import com.rybbaby.tss.platform.sysAdminUser.service.ISysAdminUserService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;


/**
 * @author 雷春琼
 * @description 会员课时包管理
 * @createDate 2017-08-10 上午12:04:35
 */
@Controller
@RequestMapping(value = "tssMemberPackageController")
public class TssMemberPackageController extends BaseController {

    @Autowired
    private ITssMemberPackageService tssMemberPackageService;
    @Autowired
    private ITssStudentService tssStudentService;
    @Autowired
    private ITssPackageService tssPackageService;
    @Autowired
    private ISysAdminUserService empSysAdminUserService;
    @Autowired
    private IViewService<ViewTssMemberPackage> viewService;
    @Autowired
    private ITssPaymentService tssPaymentService;

    @Autowired
    private IBaseService<TssMemberPackage> baseService;

    @Autowired
    private IViewMemberPackageStudentService viewMemberPackageStudentService;

    @Autowired
    private ImportExcelService importExcelService;
    @Autowired
    private ISysAdminUserService sysAdminUserService;

    /**
     * 获取会员课时包列表
     *
     * @throws IOException
     * @reourn
     */
    @RequestLog(content = "获取会员课时包列表", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "tssMemberPackageList", method = RequestMethod.POST)
    public ModelAndView tssMemberPackageList(ViewTssMemberPackage entity, PageBean paramPageBean, @RequestParam(required = true) Integer type, @RequestParam(required = false) Integer status) throws Exception {
        ModelAndView mav = null;
        try {
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(ViewTssMemberPackage.class);
            String ids = "";

            if (StringUtils.isBlank(status)) {
                dc.add(Restrictions.ne("stuStatus", 6));
                if (type == 1) {
                    //亲子会员列表
                    mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssMemberPackageListView"));
                } else if (type == 2) {
                    //过渡会员列表
                    mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitMemberPackageListView"));
                }
            }
            if (StringUtils.isNotBlank(status)) {
                dc.add(Restrictions.eq("stuStatus", 6));
                if (type == 1) {
                    //亲子历史会员列表
                    mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssHistoryMemberPackageListView"));
                } else if (type == 2) {
                    //过渡历史会员列表
                    mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitHistoryMemberPackageListView"));
                }
            }


            //获取当前登录者
            String adminUserId = super.getLoginUser().getId();

            SysAdminUser sysAdminUser = this.sysAdminUserService.get(adminUserId);
            //获取当前登录者所拥有角色
            List<String> roleList = super.getLoginAdminRoles();

            if(roleList.contains(RoleConsts.TSS_COUNSELOR)){
                dc.add(Restrictions.sqlRestriction(" empAdminUserId ='" + adminUserId + "'"));
            }else{
                List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
                ids = StringUtils.join(idsList, "','");
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + ids + "') "));
            }

            dc.addOrder(Order.desc("updateTime"));
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            PageBean pageBean = viewService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", SEARCH_FORM);
           // mav.addObject("actionUrl", "/tssMemberJoinPakcageController/toEditView.do?type=" + type + "&status=" + status);
            mav.addObject("actionUrl" , request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("memberType", type);
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
            // mav.addObject("editUrl", "/tssStudentController/toEditView.do");
           // mav.addObject("editUrl", "/tssMemberJoinPakcageController/toEditView.do?type=" + type);

        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 转到编辑视图
     *
     * @param entity       接收编辑参数的临时对象
     * @param serializeNum 请求标识
     * @return
     */
    @RequestLog(content = "转到会员课时包视图", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "toEditView", method = RequestMethod.GET)
    public ModelAndView toEditView(TssMemberPackage entity, @RequestParam(required = true) String serializeNum, @RequestParam(required = true) String targetDataId) {
        //ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssMemberPackageEditView"));
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("toPackagePaymentView"));
        //查询定金
        try {
            //List<TssPayment> payment=this.tssStudentService.findStudentByName(entity.getName());
            List<TssPayment> paymentList = this.tssPaymentService.findDepositById(entity.getId());
            double sumDeposit = 0;
            String depositIds = "";
            for (int i = 0; i < paymentList.size(); i++) {
                sumDeposit += paymentList.get(i).getAmount();
                if (i == 0) {
                    depositIds = depositIds;
                } else {
                    depositIds = depositIds + "," + paymentList.get(i).getId();
                }
            }
            mav.addObject("deposit", sumDeposit);
            mav.addObject("depositIds", depositIds);
        } catch (Exception e) {
            //throw e;
            e.printStackTrace();
        }
        mav.addObject("serializeNum", serializeNum);
        mav.addObject("targetDataId", targetDataId);
        //  mav.addObject("memberType", type);
        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }


    /**
     * 删除指定id的对象
     *
     * @param id 需要被删除的对象id
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String delete(@StringValidator(nullable = false) String id) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(id)) {
                this.tssMemberPackageService.deleteEntityById(id);
            } else {
                ajr.setResMsg("删除失败!");
                ajr.setResCode(302);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 批量删除指定id的对象
     *
     * @param ids 需要被删除的对象id组成的字符串
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "batchDelete", method = RequestMethod.GET)
    public String batchDelete(@RegexpValidator(nullable = false, regexp = "^(\\w+,?)+\\w+$") String ids) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(ids)) {
                boolean batchDelete = this.tssMemberPackageService.batchDelete(ids.split(","));
                if (!batchDelete) {
                    ajr.setResMsg("删除失败!");
                    ajr.setResCode(302);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }


    /**
     * 根据会员Id查询购买的课时包信息
     *
     * @param memberId
     * @return
     */
    @ResponseBody
    @RequestLog(content = "根据会员Id查询购买的课时包信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "getListByMemberId", method = RequestMethod.POST)
    public ModelAndView getListByMemberId(@RequestParam(required = true) String serializeNum, @RequestParam(required = true) String memberId, @RequestParam(required = true) Integer type) throws Exception {
        ModelAndView mav = null;
        try {
            if (type == 1) {
                //亲子会员列表
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssMemberAttendPackageListView"));
            } else if (type == 2) {
                //过渡会员列表
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitMemberAttendPackageListView"));
            }
            List<Map<String, Object>> memberPackagesList = this.tssMemberPackageService.getListByMemberId(memberId, type);
            mav.addObject("memberPackagesList", memberPackagesList);
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 根据会员Id查询购买的课时包信息
     *
     * @param memberId
     * @return
     */
    @ResponseBody
    @RequestLog(content = "根据会员Id查询购买的课时包信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "getUsableTotalPakcageDetailListByMemberId", method = RequestMethod.POST)
    public String getUsableTotalPakcageDetailListByMemberId(@RequestParam(required = true) String serializeNum, @RequestParam(required = true) String memberId, @RequestParam(required = true) Integer type) throws Exception {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            List<Map<String, Object>> memberPackagesList = this.tssMemberPackageService.getListByMemberId(memberId, type);
            ajr.setData(memberPackagesList.toArray());
        } catch (Exception e) {
            throw e;
        }
        return ajr.jsonResponse(true);
    }

    /**
     * 根据会员Id查询可以退费的购买课时包信息
     *
     * @param memberId
     * @return
     */
    @ResponseBody
    @RequestLog(content = "根据会员Id查询可以退费的购买课时包信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "getShouldReturnPremiumListByMemberId", method = RequestMethod.POST)
    public ModelAndView getShouldReturnPremiumListByMemberId(@RequestParam(required = true) String serializeNum, @RequestParam(required = true) String memberId, @RequestParam(required = true) Integer type) throws Exception {
        ModelAndView mav = null;
        try {
            if (type == 1) {
                //亲子会员列表
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssMemberShouldReturnPremiumPackageListView"));
            } else if (type == 2) {
                //过渡会员列表
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitMemberShouldReturnPremiumPackageListView"));
            }
            List<Map<String, Object>> memberPackagesList = this.tssMemberPackageService.getListByMemberId(memberId, type);
            mav.addObject("memberPackagesList", memberPackagesList);
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 根据会员Id查询可以加减课时的购买课时包信息
     *
     * @param memberId
     * @return
     */
    @ResponseBody
    @RequestLog(content = "根据会员Id查询可以加减课时的购买课时包信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "getShouldAddSubtractListByMemberId", method = RequestMethod.POST)
    public ModelAndView getShouldAddSubtractListByMemberId(@RequestParam(required = true) String serializeNum, @RequestParam(required = true) String memberId, @RequestParam(required = true) Integer type) throws Exception {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssMemberShouldAddSubtractPackageListView"));
        try {
            List<Map<String, Object>> memberPackagesList = this.tssMemberPackageService.getListByMemberId(memberId, type);
            mav.addObject("memberPackagesList", memberPackagesList);
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }


    /**
     * 根据状态修改课时包信息
     *
     * @param packageStatus
     * @return
     */
    @ResponseBody
    @RequestLog(content = "根据状态修改课时包信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "updatePackageStatus", method = RequestMethod.POST)
    public String updatePackageStatus(@RequestParam(required = true) String targetDateId, @RequestParam(required = true) Integer packageStatus) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("packageStatus", 1);
            map.put("updateTime", new Timestamp(System.currentTimeMillis()));
            Integer status = this.tssMemberPackageService.updateParameterById(map, targetDateId);
            if (status == null) {
                ajr.setResMsg("激活失败!");
                ajr.setResCode(302);
            } else {
                ajr.setResMsg("激活成功!");
                ajr.setResCode(200);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("激活失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(true);

    }


    /**
     * 根据id查询会员详情
     *
     * @param serializeNum
     * @param memberId
     * @param type
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestLog(content = "根据id查询会员详情", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "getMemberDetailById", method = RequestMethod.GET)
    public ModelAndView getMemberDetailById(@RequestParam(required = true) String serializeNum, @RequestParam(required = true) String memberId, @RequestParam(required = true) Integer type) throws Exception {
        ModelAndView mav = null;
        try {
            if (type == 1) {
                //亲子会员列表
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssMemberPackageDetailListView"));
            } else if (type == 2) {
                //过渡会员列表
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitMemberPackageDetailListView"));
            }
            //    List<TssMemberPackage> memberPackagesList = this.tssMemberPackageService.getListByMemberId(memberId, type);
            //     mav.addObject("memberPackagesList", memberPackagesList);
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }


    /**
     * 会员管理>亲子会员and过渡会员模块
     * 杨然
     * 2017年11月10日15:13:04
     */
    @ResponseBody
    @RequestMapping("/exportExcle")
    public void exportExcle(Integer type, String ids, Integer flag, ViewMemberPackageStudent entity, PageBean paramPageBean, HttpServletResponse response, HttpServletRequest request) throws Exception {
        List<String> stuIdList = null;
        List<ViewMemberPackageStudent> memberPackageStus = null;
        String path = "jso/export_memberPackage.json";
        String templateName = request.getParameter("templateName");

        if (ids == "") {

            if (flag == 1) {

                Map<String, String[]> unLockMap = getParameterMap(request);
                DetachedCriteria dc = DetachedCriteria.forClass(ViewMemberPackageStudent.class);
                HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
                PageBean pageBean = tssStudentService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
                memberPackageStus = (List<ViewMemberPackageStudent>) pageBean.getList();

            } else {
                memberPackageStus = viewMemberPackageStudentService.findListByType(type);
            }

        }

        //如果选择了序号 则根据序号导出该信息
        if (ids != "") {
            String[] idss = ids.split(",");
            stuIdList = Arrays.asList(idss);
            memberPackageStus = this.viewMemberPackageStudentService.findListByStuId(stuIdList);
        }

        ExportUtil export = new ExportUtil();
        export.export(path, templateName, memberPackageStus, request, response);

    }

    /**
     * 会员管理>亲子历史会员and过渡历史会员模块
     * 杨然
     * 2017年11月10日15:37:00
     */
    @ResponseBody
    @RequestMapping("/exportExcleHistory")
    public void exportExcleHistory(Integer type, String ids, Integer flag, ViewMemberPackageStudent entity, PageBean paramPageBean, HttpServletResponse response, HttpServletRequest request) throws Exception {
        ViewMemberPackageStudent viewMemberPackageStudent = null;
        List<String> stuIdList = null;
        List<ViewMemberPackageStudent> memberPackageStus = null;
        String path = "jso/export_memberPackage.json";
        String templateName = request.getParameter("templateName");

        if (ids == "") {

            if (flag == 1) {

                Map<String, String[]> unLockMap = getParameterMap(request);
                DetachedCriteria dc = DetachedCriteria.forClass(ViewMemberPackageStudent.class);
                HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
                PageBean pageBean = tssStudentService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
                memberPackageStus = (List<ViewMemberPackageStudent>) pageBean.getList();

            } else {
                memberPackageStus = viewMemberPackageStudentService.findListByType(type);
            }

        }

        //如果选择了序号 则根据序号导出该信息
        if (ids != "") {
            String[] idss = ids.split(",");
            stuIdList = Arrays.asList(idss);
            memberPackageStus = this.viewMemberPackageStudentService.findListByStuId(stuIdList);
        }

        ExportUtil export = new ExportUtil();
        export.export(path, templateName, memberPackageStus, request, response);

    }


    /**
     * 会员管理>导入功能
     * 杨然
     * 2017年11月14日16:12:55
     */
    @CrossOrigin
    @RequestMapping("/importExcel")
    @ResponseBody
    public void importExcel(HttpServletRequest request, HttpServletResponse response) {
        StringBuffer reg = null;

        String adminUserId = super.getLoginUser().getId();
        try {
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession()
                    .getServletContext());
            commonsMultipartResolver.resolveMultipart(request);
            reg = importExcelService.importManage(request, adminUserId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        response.setCharacterEncoding("UTF-8");

        try {
            response.getWriter().print(reg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出错误信息
     * 杨然
     * 2017年12月1日 14:40:38
     */
    @RequestMapping("/exportErrorMessage")
    public void exportErrorMessage(HttpServletRequest request, HttpServletResponse response) {
        String path = "jso/export_errorMessage.json";
        String templateName = "errorMessage.xlsx";

        ExportUtil export = new ExportUtil();
        ErrorMessage errorMessage = (ErrorMessage) request.getSession().getAttribute("errorMessage");
        List<ErrorMessage> errorList = new ArrayList<>();
        errorList.add(errorMessage);
        System.out.println(errorMessage);
        export.export(path, templateName, errorList, request, response);
    }

    /**
     * 会员详情-关联课时包
     */
    @RequestLog(content = "转到客户表视图", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "associationClassPackage", method = RequestMethod.GET)
    public ModelAndView associationClassPackage(TssStudent entity) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("associationClassPackageView"));

        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }
}
